package com.leiqichao.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leiqichao.backend.common.Result;
import com.leiqichao.backend.entity.StatVisit;
import com.leiqichao.backend.service.StatVisitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;

@RestController
@RequestMapping("/api/stats")
public class StatVisitController {

    private final StatVisitService statVisitService;

    @Autowired
    public StatVisitController(StatVisitService statVisitService) {
        this.statVisitService = statVisitService;
    }

    /**
     * 分页查询访问统计
     * @param start 开始日期（格式：yyyy-MM-dd）
     * @param end 结束日期（格式：yyyy-MM-dd）
     * @param page 页码（默认1）
     * @param size 每页数量（默认10）
     */
    @GetMapping("/visits")
    public Result<IPage<StatVisit>> getVisitStats(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate start,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size
    ) {
        // 1. 参数校验
        if (start == null || end == null) {
            return Result.error(400, "日期参数不能为空");
        }
        if (start.isAfter(end)) {
            return Result.error(400, "开始日期不能晚于结束日期");
        }

        // 2. 构建分页参数
        Page<StatVisit> pageParam = new Page<>(page, size);

        // 3. 构建查询条件
        QueryWrapper<StatVisit> query = new QueryWrapper<>();
        query.between("date", start, end)
                .orderByDesc("date");

        // 4. 执行分页查询
        IPage<StatVisit> result = statVisitService.page(pageParam, query);

        // 5. 处理空数据
        if (result.getRecords().isEmpty()) {
            return Result.notFound();
        }

        return Result.success(result);
    }

    @GetMapping("/visits/today")
    public Result<Long> getTodayVisitStats() {
        return Result.success( statVisitService.getDailyAccessCount());
    }

}